<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/5/23 0023
 * Describe: 签名管理类.
 */

namespace app\api\controller\efficiency;

use think\Controller;
use think\Db;
use think\Request;

/*
 * 参数验证管理类
 * */
class Sign extends Controller
{
//  mec_id值
    protected $mec_id = 'a260e907ed68ff61c68e8068e96be94b';
//    key值
    protected $key = '3bc2e785f1698666310539c0f2496689';
//    版本号
    protected $version = '2.0.0';
//    渠道标识
    private $cid = 'eb111cf180a473a6484c71ef2c6aebfe';
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->selectSi();
    }
    private function selectSi(){
        $data = Db::table('xb_sys_integrate')
            ->alias('sig')
            ->join('xb_sys_inteparameter sip','sig.id=sip.IntegrateID')
            ->where('sig.Name="效率花呗"')
            ->select();
        if (!empty($data)){
            foreach ($data as $v){
                if ($v['ParaName'] == 'mec_id'){
                    $this->mec_id = $v['ParaValue'];
                }elseif ($v['ParaName'] == 'key'){
                    $this->key = $v['ParaValue'];
                }elseif ($v['ParaName'] == 'version'){
                    $this->version = $v['ParaValue'];
                }
            }
        }
    }
    /*
     * 添加用户签名验签
     * */
    public function verifyUserSignature($data = []){
        if (empty($data)) return false;
//        请求时间超时
        if(!isset($data['request_time']) || time()-$data['request_time'] > 60) return 101;
//        签名
        $signature = md5($this->cid.$data['request_time'].$data['phone']);
        return $signature == $data['sign'] ? 0 : 11;
    }
    /*
     *参数加密
     * */
    public function SignEncrypt($data = [],$type){
        if (empty($data)) return [];
        $time = time();
        switch ($type){
            case 1://用户注册状态
                $data['sign'] = md5($this->key.$time.$this->version.$data['phone'].$time);
                break;
            case 2://用户申请贷款
                $data['sign'] = md5($this->key.$data['request_time'].$this->version.$data['phone'].$data['loan_sn'].$data['apply_time']);
                break;
            case 3://用户申请贷款结果
                $data['sign'] = md5($this->key.$data['request_time'].$this->version.$data['phone'].$data['loan_sn'].$data['review_time'].$data['review_status']);
                break;
            case 4://用户还款结果
                $data['sign'] = md5($this->key.$data['request_time'].$this->version.$data['phone'].$data['loan_sn'].$data['repayment_time'].$data['repayment_status']);
                break;
        }
        $data['mec_id']=$this->mec_id;
        $data['version']=$this->version;
        return $data;
    }

}
